package com.bigegg.employee.service.impl;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysRoleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 角色 service
 *
 * @author sun
 */

@Service
public class CRoleService {

    private final Logger logger = LoggerFactory.getLogger(CRoleService.class);


    // roleService 中没有无用户查询所有角色的方法，采用直接调用dao层
    @Autowired
    private SysRoleMapper sysRoleMapper;


    @Autowired
    CUserService cUserService;

    /**
     * 根据 TypeUserService接口的实现类，来初始化创建系统角色。
     */
    @EventListener(value = ApplicationStartedEvent.class)
    public void initRoles() {
        String[] userTypeNames = cUserService.getUserTypeNames();
        logger.info("初始化角色 [{}] ", StringUtils.join(userTypeNames, ","));
        List<SysRole> roles = sysRoleMapper.selectRoleAll();
        for (String userTypeName : userTypeNames) {
            if (roles.stream().noneMatch(one -> one.getRoleName().equals(userTypeName))) {
                SysRole role = new SysRole();
                role.setRoleName(userTypeName);
                role.setRoleKey("K_" + userTypeName);
                role.setRoleSort("99");
                role.setStatus("0");
                role.setCreateTime(new Date());
                role.setRemark("根据用户的类型系统自动创建，切勿对改角色进行修改、删除！");
                sysRoleMapper.insertRole(role);
                logger.info("已成功创建角色 [{}] ", userTypeName);
                continue;
            }
            logger.info("系统已存在角色 [{}]，无需创建！ ", userTypeName);
        }
    }

    /**
     * 获取 Role 对象
     * @param roleName 角色名称
     * @return SysRole
     */
    public SysRole getRoleByName(String roleName) {
        SysRole sysRole = new SysRole();
        sysRole.setRoleName(roleName);
        List<SysRole> roles = sysRoleMapper.selectRoleList(sysRole);
        return roles == null || roles.size() < 1 ? null: roles.get(0);
    }
}
